﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http.Routing;
using Cofe.Core.Utils;

namespace Cofe.Web.Utils
{
    //http://stackoverflow.com/questions/15681330/webapi-controller-with-two-get-actions
    public class GuidConstraint : IHttpRouteConstraint
    {        
        private static Regex isGuid = new Regex(RegexPatterns.GuidPattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);

        public bool Match(HttpRequestMessage request, IHttpRoute route, string parameterName, IDictionary<string, object> values,
                          HttpRouteDirection routeDirection)
        {
            if (values.ContainsKey(parameterName))
            {
                if (values[parameterName] is Guid)
                    return true;

                string stringValue = values[parameterName] as string;

                if (!string.IsNullOrEmpty(stringValue))
                {
                    return isGuid.Match(stringValue).Success;
                }
            }

            return false;
        }
    }
}